<?php
namespace console\controllers;

use backend\models\QuestionVideoModel;
use Yii;
use backend;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use backend\models\UserCouponModel;
use backend\models\CourseVideoModel;
use backend\models\CourseModel;
use backend\models\PlayRecordModel;
use backend\models\OrdersModel;
use backend\models\UserModel;
use backend\models\TeacherModel;
use backend\models\OrdersIncomeModel;
use backend\models\CourseClassModel;
use backend\models\StatisticsCourseModel;
use backend\models\StatisticsCourseVideoModel;
use backend\models\StatisticsPaidModel;
use backend\models\StatisticsTeacherModel;
use backend\models\TeacherVideoModel;
use backend\models\StatisticsUserModel;
use backend\models\StatisticsSqOldUserPriceModel;
use backend\models\StatisticsSqUserCashModel;

/**
 * 定时脚本任务
 */
class CrontabController extends \yii\console\Controller
{
    public $yesterday = 0;

    public function init()
    {
        parent::init();
        //昨天0点时间戳
        $this->yesterday = strtotime(date('Y-m-d'))-86400;
    }

    public function actionAddVideoPlayCount()
    {
        $list = CourseVideoModel::find()->select('id,play_count,course_id')->where(['is_checked'=>1,'status_shelves'=>1,'is_delete'=>0])->orderBy('rand()')->limit(100)->asArray()->all();
        if($list){
            $course=$video=$course_data=$video_data=[];
            foreach($list as $item){
                $count = 1;//可以使用随机播放数
                if(!isset($course[$item['course_id']])){
                    $course[$item['course_id']] = 0;
                }
                $course[$item['course_id']] += $count;
                $video[$item['id']] = $count;
            }
            //ID和数量互换
            foreach($course as $id => $count){
                if($id > 0){
                    $course_data[$count][] = $id;
                }
            }
            foreach($video as $id => $count){
                if($id > 0){
                    $video_data[$count][] = $id;
                }
            }
            //更新
            foreach($course_data as $count => $ids){
                Yii::$app->db->createCommand("UPDATE `".CourseModel::tableName()."` SET `play_num`=`play_num`+$count WHERE `id` in (".implode(',',$ids).")")->execute();
            }
            foreach($video_data as $count => $ids){
                Yii::$app->db->createCommand("UPDATE `".CourseVideoModel::tableName()."` SET `play_count`=`play_count`+$count WHERE `id` in (".implode(',',$ids).")")->execute();
            }
        }
    }

    /**
     * 题库图片镜像下载
     */
    public function actionTikuImage()
    {
        function getImageStatus($url){
            $oss_host = Yii::$app->params['oss']['root_domain'];
            $url = str_replace('http://tikucommon-zs.oss-cn-beijing.aliyuncs.com/tiku',$oss_host.'tiku',$url);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_NOSIGNAL, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 300);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Range: bytes=0-1'));
            curl_exec($ch);
            $info = curl_getinfo($ch);
            curl_close($ch);
            if(!empty($info['http_code']) && in_array($info['http_code'],[200,206])){
                return true;
            }
            return false;
        }
        $table = '';
        $id = 0;
        $oss_host = Yii::$app->params['oss']['root_domain_s'];//'http://oss.51koudaishu.com';
        $gz = '/(http:\/\/tikucommon-zs\.oss-cn-beijing\.aliyuncs\.com\/tiku\/.*\.(jpg|png|jpeg|bmp|gif))/Ui';
        try{
            foreach(['czdl','czhx','czls','czsw','czsx','czwl','czyw','czyy','czzz','gzdl','gzhx','gzls','gzsw','gzsx','gzwl','gzyw','gzyy','gzzz','xxsx','xxyw','xxyy'] as $tab){
                $table = 'questions_'.$tab;
                $id = 0;
                file_put_contents('./backend/runtime/logs/tiku_image_id.txt',"table:".$table."  id:".$id." \n",FILE_APPEND);
                while(true){
                    $list = (new \yii\db\Query())
                    ->select(['id', 'body_html','answer_html','anylysis_html'])
                    ->from($table)
                    ->andWhere(['>','id',$id])//->andWhere(['id'=>55164334])
                    ->orderBy('id asc')
                    ->limit(100)
                    ->all();
                    if(empty($list)){
                        break;
                    }
                    foreach($list as $key => $item){
                        $id = $item['id'];
                        $error = 0;
                        $success = 0;
                        if(!empty($item['body_html']) && preg_match_all($gz,$item['body_html'],$images) && !empty($images[1])){
                            foreach($images[1] as $img){
                                if(!getImageStatus($img)){
                                    ++$error;
                                }else{
                                    ++$success;
                                }
                            }
                        }
                        if(!empty($item['answer_html']) && preg_match_all($gz,$item['answer_html'],$images) && !empty($images[1])){
                            foreach($images[1] as $img){
                                if(!getImageStatus($img)){
                                    ++$error;
                                }else{
                                    ++$success;
                                }
                            }
                        }
                        if(!empty($item['anylysis_html']) && preg_match_all($gz,$item['anylysis_html'],$images) && !empty($images[1])){
                            foreach($images[1] as $img){
                                if(!getImageStatus($img)){
                                    ++$error;
                                }else{
                                    ++$success;
                                }
                            }
                        }
                        if($error > 0){
                            Yii::$app->db->createCommand("UPDATE `{$table}` SET `status`='4' WHERE (`id`='{$item['id']}')")->execute();
                        }else if($success > 0){
                            Yii::$app->db->createCommand("UPDATE `{$table}` SET
                                `body_html`=replace(`body_html`,'http://tikucommon-zs.oss-cn-beijing.aliyuncs.com/tiku','{$oss_host}tiku'),
                                `answer_html`=replace(`answer_html`,'http://tikucommon-zs.oss-cn-beijing.aliyuncs.com/tiku','{$oss_host}tiku'),
                                `anylysis_html`=replace(`anylysis_html`,'http://tikucommon-zs.oss-cn-beijing.aliyuncs.com/tiku','{$oss_host}tiku')
                                WHERE (`id`='{$item['id']}')")->execute();
                        }
                    }
                }
            }

        }catch(\Exception $e){
            file_put_contents('./backend/runtime/logs/tiku_image_error.txt',$e->getMessage()." \ntable:".$table." \nid:".$id." \n\n\n",FILE_APPEND);
        }
    }

//    /**
//     * solr定时增量索引
//     */
//    public function actionSolrDeltaImport()
//    {
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, "http://localhost:8983/solr/kds/deltaimport?command=delta-import&clean=false&commit=true" );
//        curl_setopt($ch, CURLOPT_HEADER, false);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        curl_setopt($ch, CURLOPT_NOSIGNAL, true);
//        curl_setopt($ch, CURLOPT_TIMEOUT, 99999);
//        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization:Basic YWRtaW46a2RzMDU3MQ=='));
//        $output = curl_exec($ch);
//        curl_close($ch);
//        var_dump($output);
//    }

    /**
     * 课程分类隐藏
     */
    public function actionCourseClassHidden()
    {
        $data = [];
        $tr = Yii::$app->db->beginTransaction();
        $res1 = CourseClassModel::updateAll(['is_course'=>0]);
        $res2 = (array)CourseVideoModel::find()->select('DISTINCT(class_id)')->where('class_id >0 and course_id=0 and is_checked=1 and is_delete=0 and status_shelves=1')->column();
        $res3 = (array)CourseModel::find()->select('DISTINCT(class_id)')->where('is_checked=1 and is_delete=0')->column();
        $ids = array_unique(array_merge($res2,$res3));
        if($res1 !== false && $ids){
            foreach($ids as $id){
                array_push($data,$id,substr($id,0,2).'000000',substr($id,0,4).'0000',substr($id,0,6).'00');
                $data[] = $id;
            }
            $data = array_unique($data);
            $res = CourseClassModel::updateAll(['is_course'=>1],['in','id',$data]);
            if($res !== false){
                $tr->commit();
                return true;
            }
        }
        $tr->rollBack();
    }

    /**
     * 设置视频播放链接
     * @return string
     * @throws \yii\base\Exception
     */
    public function actionSetVideoFilesrc(){
//        $body = file_get_contents('php://input');
//        //file_put_contents('./test.txt',$body."\n\n\n",FILE_APPEND);
//        if($body){
//            $data = json_decode($body,true);
//            if(!empty($data) && isset($data['EventType'])){
//                //mp4转码完成
//                if($data['EventType'] == 'StreamTranscodeComplete' && isset($data['Format']) && $data['Format'] == 'mp4' && isset($data['VideoId']) && $data['VideoId'] !='' && isset($data['FileUrl']) && $data['FileUrl'] !=''){
//                    $res = CourseVideoModel::findOne(['video_id'=>$data['VideoId']]);
//                    if($res){
//                        $res->filesrc = $data['FileUrl'];
//                        $res->duration = isset($data['Duration']) ? intval($data['Duration']) : 0;
//                        $res->size = isset($data['Size']) ? intval($data['Size'] / 1024) : 0;
//                        $res->save();
//                    }
//                }
//            }
//        }
//        return 'SUCCESS';
        $list = CourseVideoModel::find()->where('filesrc = "" AND video_id != ""')->all();
        if($list){
            foreach($list as $item){
                if(!$item->video_id) continue;
                $res = CourseVideoModel::vetPlayInfo(['video_id'=>$item->video_id]);
                if(isset($res->PlayURL) && !empty($res->PlayURL)){
                    $item->filesrc = $res->PlayURL;
                    $item->duration = intval($res->Duration);
                    $item->size = intval($res->Size / 1024);
                    var_dump($item->save());
                }
            }
        }
    }

    /**
     * 设置题目解析视频地址
     * @return string
     * @throws \yii\base\Exception
     */
    public function actionSetQuestionFilesrc(){
        $question_list = QuestionVideoModel::find()->where('filesrc = "" AND video_id != ""')->all();
        if($question_list){
            foreach($question_list as $item){
                if(!$item->video_id) continue;
                $res = QuestionVideoModel::vetPlayInfo(['video_id'=>$item->video_id]);
                if(isset($res->PlayURL) && !empty($res->PlayURL)){
                    $item->filesrc = $res->PlayURL;
                    $item->duration = intval($res->Duration);
                    $item->size = intval($res->Size / 1024);
                    var_dump($item->save());
                }
            }
        }
    }

    /**
     * 设置老师微课堂视频地址
     * @return string
     * @throws \yii\base\Exception
     */
    public function actionSetTeacherFilesrc(){
        $teacher_list = TeacherVideoModel::find()->where('filesrc = "" AND video_id != ""')->all();
        if($teacher_list){
            foreach($teacher_list as $item){
                if(!$item->video_id) continue;
                $res = TeacherVideoModel::vetPlayInfo(['video_id'=>$item->video_id]);
                if(isset($res->PlayURL) && !empty($res->PlayURL)){
                    $item->filesrc = $res->PlayURL;
                    $item->duration = intval($res->Duration);
                    $item->size = intval($res->Size / 1024);
                    var_dump($item->save());
                }
            }
        }
    }


    /**
     * 设置老师微课堂视频封面
     * @return string
     * @throws \yii\base\Exception
     */
    public function actionSetTeacherVideoImage(){
        $list = TeacherVideoModel::find()->where('(image = "" OR image IS NULL) AND (video_id != "" && video_id IS NOT NULL)')->limit(100)->all();
        if($list){
            $oss = new backend\models\OssModel();
            foreach($list as $item){
                if(!$item->video_id) continue;
                $res = TeacherVideoModel::getVideoInfo(['video_id'=>$item->video_id]);
                if(isset($res->CoverURL) && !empty($res->CoverURL)){
                    $oss_image = $oss->upload_remote_img($res->CoverURL);
                    $item->image = $oss_image ? : $res->CoverURL;
                    var_dump($item->save());
                }
            }
        }
    }


    /**
     * 设置视频封面
     * @return string
     * @throws \yii\base\Exception
     */
    public function actionSetVideoImage(){
        $list = CourseVideoModel::find()->where('(image = "" OR image IS NULL) AND (video_id != "" && video_id IS NOT NULL)')->limit(100)->all();
        if($list){
            $oss = new backend\models\OssModel();
            foreach($list as $item){
                if(!$item->video_id) continue;
                $res = CourseVideoModel::getVideoInfo(['video_id'=>$item->video_id]);
                if(isset($res->CoverURL) && !empty($res->CoverURL)){
                    $oss_image = $oss->upload_remote_img($res->CoverURL);
                    $item->image = $oss_image ? : $res->CoverURL;
                    var_dump($item->save());
                }
            }
        }
    }

    /**
     * 定时删除旧图片
     */
    public function actionDeleOldImage()
    {
        $oss = new backend\models\OssModel();
        $list = $oss->deleOldImage($oss);
        var_dump($list);exit;
    }

    /**
     * 定时删除旧图片
     */
    public function actionDeleOldVideo()
    {
        CourseVideoModel::deleOldVideo();
    }

    /**
     * 统计课程
     */
    public function actionStatisticsCourse()
    {
//        $this->yesterday = strtotime('2017-09-01 00:00:00');
//        while($this->yesterday < (time()-86400)){
            $model = new StatisticsCourseModel();
            $total_num = (int)StatisticsCourseModel::find()->select('total_num')->orderBy('id DESC')->scalar();
            $model->increment_num = (int)CourseModel::find()->where('create_time between '.$this->yesterday.' and '.($this->yesterday+86399))->count();
            $model->total_num = $total_num + $model->increment_num;
            $model->date = $this->yesterday;
            $model->update_time = $model->create_time = time();
            $model->save();
//            $this->yesterday += 86400;
//        }
    }

    /**
     * 统计视频
     */
    public function actionStatisticsCourseVideo()
    {
        $model = new StatisticsCourseVideoModel();
        $total = StatisticsCourseVideoModel::find()->select('total_num,total_duration,total_play_num,total_play_duration')->orderBy('id DESC')->one();
        //视频新增增量和总量
        $model->increment_num = (int)CourseVideoModel::find()->where('create_time between '.$this->yesterday.' and '.($this->yesterday+86399))->count();
        $model->total_num = ($total ? $total->total_num : 0) + $model->increment_num;
        //视频新增时长增量和总量
        $model->increment_duration = (int)CourseVideoModel::find()->where('create_time between '.$this->yesterday.' and '.($this->yesterday+86399))->sum('duration');
        $model->total_duration = ($total ? $total->total_duration : 0) + $model->increment_duration;
        //视频播放次数增量和总量
        $play_record = PlayRecordModel::find()->select('count(0) c, sum(time_length) time_length')->where('create_time between '.$this->yesterday.' and '.($this->yesterday+86399))->asArray()->one();
        $model->increment_play_num = $play_record ? $play_record['c'] : 0;
        $model->total_play_num = ($total ? $total->total_play_num : 0) + $model->increment_play_num;
        //视频播放时长增量和总量
        $model->increment_play_duration = $play_record ? (int)$play_record['time_length'] : 0;
        $model->total_play_duration = ($total ? $total->total_play_duration : 0) + $model->increment_play_duration;
        //日期
        $model->date = $this->yesterday;
        $model->update_time = $model->create_time = time();
        $model->save();
    }


    /**
     * 统计付费
     */
    public function actionStatisticsPaid()
    {
        $model = new StatisticsPaidModel();
        $total = StatisticsPaidModel::find()->select('total_num')->orderBy('id DESC')->one();
        //付费金额增量和总量
        $orders = OrdersModel::find()->select('sum(amount_paid) amount_paid')->where('create_time between '.$this->yesterday.' and '.($this->yesterday+86399).' AND is_paid=1')->asArray()->one();
        $model->increment_num = $orders ? (double)$orders['amount_paid'] : 0;
        $model->total_num = ($total ? $total->total_num : 0) + $model->increment_num;
        //日期
        $model->date = $this->yesterday;
        $model->update_time = $model->create_time = time();
        $model->save();
    }

    /**
     * 统计老师
     */
    public function actionStatisticsTeacher()
    {
        $model = new StatisticsTeacherModel();
        $total_num = (int)StatisticsTeacherModel::find()->select('total_num')->orderBy('id DESC')->scalar();
        $model->increment_num = (int)TeacherModel::find()->where('create_time between '.$this->yesterday.' and '.($this->yesterday+86399))->count();
        $model->total_num = $total_num + $model->increment_num;
        $model->date = $this->yesterday;
        $model->update_time = $model->create_time = time();
        $model->save();
    }

    /**
     * 统计学生
     */
    public function actionStatisticsUser()
    {
        $model = new StatisticsUserModel();
        $total_num = (int)StatisticsUserModel::find()->select('total_num')->orderBy('id DESC')->scalar();
        $model->increment_num = (int)UserModel::find()->where('create_time between '.$this->yesterday.' and '.($this->yesterday+86399))->count();
        $model->total_num = $total_num + $model->increment_num;
        $model->date = $this->yesterday;
        $model->update_time = $model->create_time = time();
        $model->save();
    }

    /**
     * 统计优惠券
     */
    public function actionStatisticsUserCoupon()
    {
        $time = time();
        $list = [];
        $field = ['date','coupon_id','create_num','use_num','expire_num','create_time'];
        $create_list = UserCouponModel::find()->select('coupon_id,count(0) c')->where('create_time between '.$this->yesterday.' and '.($this->yesterday+86399))->groupBy('coupon_id')->asArray()->all();
        $use_list = UserCouponModel::find()->select('coupon_id,count(0) c')->where('is_use=2 and use_time between '.$this->yesterday.' and '.($this->yesterday+86399))->groupBy('coupon_id')->asArray()->all();
        $expire_list = UserCouponModel::find()->select('coupon_id,count(0) c')->where('expire_time between '.$this->yesterday.' and '.($this->yesterday+86399))->groupBy('coupon_id')->asArray()->all();
        if(!empty($create_list)){
            foreach($create_list as $key => $data){
                $list[$data['coupon_id']]['create_num'] = $data['c'];
            }
        }
        if(!empty($use_list)){
            foreach($use_list as $key => $data){
                $list[$data['coupon_id']]['use_num'] = $data['c'];
            }
        }
        if(!empty($expire_list)){
            foreach($expire_list as $key => $data){
                $list[$data['coupon_id']]['expire_num'] = $data['c'];
            }
        }
        if(!empty($list)){
            foreach($list as $key => $data){
                self::batchInsert('statistics_user_coupon',$field,[$this->yesterday,$key,isset($data['create_num'])?$data['create_num']:0,isset($data['use_num'])?$data['use_num']:0,isset($data['expire_num'])?$data['expire_num']:0,$time]);
            }
            self::batchInsert('statistics_user_coupon',$field,[],true);
        }
    }

    /**
     * 统计区域用户注册数
     */
    public function actionStatisticsAreaUser()
    {

//        $this->yesterday = strtotime('2017-09-01 00:00:00');
//        while($this->yesterday < (time()-86400)){
            $time = time();
            $field = ['date','province','city','country','num','update_time','create_time'];
            $res = UserModel::find()
                    ->select('province,city,country,count(0) as num')
                    ->andWhere(['>','province',0])
                    ->andWhere(['>','city',0])
                    ->andWhere(['>','country',0])
                    ->andWhere(['between','create_time',$this->yesterday,$this->yesterday+86399])
                    ->groupBy('province,city,country')
                    ->asArray()->all();
            if($res){
                foreach($res as $key => $data){
                    self::batchInsert('statistics_area_user',$field,[$this->yesterday,$data['province'],$data['city'],$data['country'],$data['num'],$time,$time]);
                }
                self::batchInsert('statistics_area_user',$field,[],true);
            }
//            $this->yesterday += 86400;
//        }
    }

    /**
     * 统计区域老师注册数
     */
    public function actionStatisticsAreaTeacher()
    {

//        $this->yesterday = strtotime('2017-09-01 00:00:00');
//        while($this->yesterday < (time()-86400)){
            $time = time();
            $field = ['date','province','city','country','num','update_time','create_time'];
            $res = TeacherModel::find()->alias('t')
                    ->select('u.province,u.city,u.country,count(0) as num')
                    ->innerJoin('user u','t.user_id=u.id')
                    ->andWhere(['>','u.province',0])
                    ->andWhere(['>','u.city',0])
                    ->andWhere(['>','u.country',0])
                    ->andWhere(['between','u.create_time',$this->yesterday,$this->yesterday+86399])
                    ->groupBy('u.province,u.city,u.country')
                    ->asArray()->all();
            if($res){
                foreach($res as $key => $data){
                    self::batchInsert('statistics_area_teacher',$field,[$this->yesterday,$data['province'],$data['city'],$data['country'],$data['num'],$time,$time]);
                }
                self::batchInsert('statistics_area_teacher',$field,[],true);
            }
//            $this->yesterday += 86400;
//        }
    }

    /**
     * 统计代理商收益数
     */
    public function actionStatisticsAgentIncome()
    {

//        $this->yesterday = strtotime('2017-09-01 00:00:00');
//        while($this->yesterday < (time()-86400)){
            $time = time();
            $field = ['date','agent_id','country_id','type','num','update_time','create_time'];
            $data=[];
            $query = OrdersIncomeModel::find()->select('orders_id,teacher_id,agent_id_student_in_area,agent_id_teacher_in_area,agent_amount_student_in_area,agent_amount_teacher_in_area')
                        ->orWhere(['>','agent_id_student_in_area',0])->orWhere(['>','agent_id_teacher_in_area',0])
                        ->andWhere(['between','create_time',$this->yesterday,$this->yesterday+86399]);
            foreach($query->each(100) as $key => $item){
                //老师注册所在区域
                if($item->agent_id_teacher_in_area > 0){
                    $country = empty($item->teacherUser->country) ? 0 : $item->teacherUser->country;
                    if($country > 0){
                        if(empty($data[$item->agent_id_teacher_in_area]['teacher'][$country])){
                            $data[$item->agent_id_teacher_in_area]['teacher'][$country] = 0;
                        }
                        $data[$item->agent_id_teacher_in_area]['teacher'][$country] += $item->agent_amount_teacher_in_area;
                    }
                }
                //学生注册所在区域
                if($item->agent_id_student_in_area > 0){
                    $country = empty($item->orders->user->country) ? 0 : $item->orders->user->country;
                    if($country > 0){
                        if(empty($data[$item->agent_id_student_in_area]['student'][$country])){
                            $data[$item->agent_id_student_in_area]['student'][$country] = 0;
                        }
                        $data[$item->agent_id_student_in_area]['student'][$country] += $item->agent_amount_student_in_area;
                    }
                }
            }
            if($data){
                foreach($data as $key => $item){
                    if(!empty($item['teacher'])){
                        foreach($item['teacher'] as $k=>$v){
                            self::batchInsert('statistics_agent_income',$field,[$this->yesterday,$key,$k,1,$v,$time,$time]);
                        }
                    }
                    if(!empty($item['student'])){
                        foreach($item['student'] as $k=>$v){
                            self::batchInsert('statistics_agent_income',$field,[$this->yesterday,$key,$k,0,$v,$time,$time]);
                        }
                    }
                }
                self::batchInsert('statistics_agent_income',$field,[],true);
//            }
//            $this->yesterday += 86400;
        }
    }


    /**
     * 统计暑假包邀请中奖
     */
    public function actionStatisticsSqUserCash()
    {
//        $this->yesterday = strtotime('2018-08-01 00:00:00');
//        while($this->yesterday < (time()-86400)){
        $model = new StatisticsSqUserCashModel();
        $total = StatisticsSqUserCashModel::find()->select('total_num,total_price')->orderBy('id DESC')->one();
        //红包数增量和总量
        $model->increment_num = (int)backend\models\ActiviteUserCashModel::find()->where('create_time between '.$this->yesterday.' and '.($this->yesterday+86399))->count();
        $model->total_num = ($total ? $total->total_num : 0) + $model->increment_num;
        //红包金额增量和总量
        $model->increment_price = (int)backend\models\ActiviteUserCashModel::find()->where('create_time between '.$this->yesterday.' and '.($this->yesterday+86399))->sum('price');
        $model->total_price = ($total ? $total->total_price : 0) + $model->increment_price;
        //日期
        $model->date = $this->yesterday;
        $model->update_time = $model->create_time = time();
        $model->save();
//        $this->yesterday += 86400;
//        }
    }


    /**
     * 统计暑假包邀请中奖
     */
    public function actionStatisticsSqOldUserPrice()
    {
//        $this->yesterday = strtotime('2018-08-01 00:00:00'); 
//        while($this->yesterday < (time()-86400)){
        $model = new StatisticsSqOldUserPriceModel();
        $total = StatisticsSqOldUserPriceModel::find()->select('total_num,total_price')->orderBy('id DESC')->one();
        //老用户累计半价数增量和总量
        $model->increment_num = (int)backend\models\ActiviteOrderModel::find()->where('status = 1 and old_user_dec_price>0 and pay_time between '.$this->yesterday.' and '.($this->yesterday+86399))->count();
        $model->total_num = ($total ? $total->total_num : 0) + $model->increment_num;
        //老用户累计半价金额增量和总量
        $model->increment_price = (int)backend\models\ActiviteOrderModel::find()->where('status = 1 and old_user_dec_price>0 and pay_time between '.$this->yesterday.' and '.($this->yesterday+86399))->sum('old_user_dec_price');
        $model->total_price = ($total ? $total->total_price : 0) + $model->increment_price;
        //日期
        $model->date = $this->yesterday;
        $model->update_time = $model->create_time = time();
        $model->save();
//        $this->yesterday += 86400;
//        }
    }

    private static $insert_data = [];
    private static function batchInsert($table,$field,$data,$run=false)
    {
        if($run==true){
            if(!empty(self::$insert_data[$table])){
                Yii::$app->db->createCommand()->batchInsert($table, $field, self::$insert_data[$table])->execute();
                unset(self::$insert_data[$table]);
            }
            return true;
        }
        self::$insert_data[$table][]=$data;
        if(count(self::$insert_data[$table]) >= 100){
            Yii::$app->db->createCommand()->batchInsert($table, $field, self::$insert_data[$table])->execute();
            unset(self::$insert_data[$table]);
        }
        return true;
    }
}